/*
 *太原学院计算机技术系  （C）  版权所有
 */
package cn.edu.tyu.finance.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.plaf.basic.BasicInternalFrameTitlePane.IconifyAction;

import com.mysql.cj.exceptions.CJConnectionFeatureNotAvailableException;
import com.mysql.cj.xdevapi.Result;

/**
 *数据库实用类
 * @author duhaohao
 * @version 1.0
 */
public class DbUtil {
	/**
	 * 获取到数据库的连接
	 * 
	 * @return 数据库连接对象
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			// 注册驱动
			Class.forName("com.mysql.cj.jdbc.Driver");

			// 读取数据库连接

			String url = "jdbc:mysql://localhost:3306/financedb?characterEncoding=utf8&serverTimezone=UTC&useUnicode=true&useSSL=false";
			// ctrl+2
			conn = DriverManager.getConnection(url, "root", "root");

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭数据库连接、预编译对象和结果集
	 * @param conn 数据库连接
	 * @param ps 预编译对象
	 * @param rs 结果集
	 */
	public static void backConn(Connection conn, PreparedStatement ps, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (ps != null) {
			try {
				ps.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		Connection conn = DbUtil.getConnection();
		System.out.println(conn);
	}
}
